package com.yxc.easyexceldemo.const_enum;

import com.yxc.easyexceldemo.annotations.EasyExcelEnumDataSource;

import java.util.HashMap;
import java.util.Map;

/**
 * 部门的列表数据
 *
 * @author: YXC
 * @time: 2022/11/16 15:06
 **/
public class DepartmentDataEnum implements EasyExcelEnumDataSource.EasyExcelEnumData<String, Integer> {

    public static final Integer UNKNOWN_CODE = -999;

    public static final String UNKNOWN_NAME = "未知";

    /**
     * nameCode缓存
     */
    static final Map<String, Integer> NAME_CODE_MAP = new HashMap<>();

    /**
     * codeName缓存
     */
    static final Map<Integer, String> CODE_NAME_MAP = new HashMap<>();
    /**
     * 缓存时间
     */
    static final Long CACHE_TIME = 60000L;
    /**
     * 是否已经缓存
     */
    static boolean isCache = false;
    /**
     * 上一次缓存时间
     */
    static Long cacheTime = 0L;

    public DepartmentDataEnum() {
        // 没有缓存，去缓存
        if (!isCache || System.currentTimeMillis() - cacheTime > CACHE_TIME ) {
            // 填充以上两个map，如果要调用spring管理的对象，使用SpringbootContent
            // SpringContextHolder.getBean("xxxService")
            // 手动填充
            NAME_CODE_MAP.put("宣传部", 1);
            NAME_CODE_MAP.put("体育部", 2);

            // 翻转填充另一个
            for (Map.Entry<String, Integer> entry : NAME_CODE_MAP.entrySet()) {
                CODE_NAME_MAP.put(entry.getValue(), entry.getKey());
            }
            isCache = true;
            cacheTime = System.currentTimeMillis();
        }
    }

    public static void resetCache() {
        isCache = false;
    }

    @Override
    public String getNameByCode(Integer code) {
        return CODE_NAME_MAP.getOrDefault(code, UNKNOWN_NAME);
    }

    @Override
    public Integer getCodeByName(String name) {
        return NAME_CODE_MAP.getOrDefault(name, UNKNOWN_CODE);
    }
}
